/**
 * Created by Administrator on 13-12-26.
 */
var gui = require('nw.gui');
var loginwin = gui.Window.get();
var homewin = null;
var loginuser={};
onload = function () {
    loginwin.show();
}
var errormap = {
    '3': '用户已经登录，请勿重复登录',
    '2': '网络错误,无法登录',
    '1': '用户名密码错误',
    '0': '密码错误'
};


var socket = io.connect('http://192.168.1.102:10001', {
    'reconnection delay': 2000,
    'force new connection': true
});
socket.on('connect', function () {
    console.log("user connected");
});

socket.on('disconnect', function () {
    socket.emit('logoutEvent', "i 'm logout");

});
socket.on('error', function () {
    $("#errors").html(errormap[2]);

});

socket.on('loginFail', function (data) {
    var code = data.trim() || 0;
    $("#errors").html(errormap[code]).show();
});

socket.on('logoutEvent',function(data){
    loginwin.hide();
    setTimeout("closelast()",4000);

});

socket.on('loginSuccess', function (data) {

    appendLogin(data);
    home({socket:socket,user:loginuser});
    //loginwin.hide();
});

function appendLogin(data) {

    loginuser['name'] = data.username;
    loginuser['password'] = data.password;
    loginuser['groupName']=data.groupName;
    loginuser['localName']=data.localName;


}

function login(event) {
    var lu = {username:$('#username').val(),password:$('#password').val()};

    socket.emit('loginEvent', lu);

}

function logout(event){
    loginwin.close(true);
}

function closelast(){
    loginwin.close(true);
}
function home(data){
    var mw = 300, mh = 600;
    if (homewin == null) {
        homewin = gui.Window.open(
            "home.html",
            {
                frame: false,
                toolbar: true,
                show: false,
                show_in_taskbar: true,
                'always-on-top': true,
                resizable:false,
                width: mw,
                height: mh
            }

        );

    }
    global.homedata=data;
    homewin.show();
}